package com.lyk.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.entity.A_customer;
import com.common.entity.PageBean;
import com.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.lyk.service.A_customerService;
import com.lyk.service.impl.A_customerServiceImpl;



public class A_customerServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out=resp.getWriter();
		String opr=request.getParameter("opr");
		if("del".equals(opr)){
			A_customerService customerService = new A_customerServiceImpl();
			int num = 0;
			String errMsg = "";
			try{
				Integer n = StringUtils.str2Integer(request.getParameter("customer_id"),0);
				if(n != null){
					num = customerService.delA_customer(n);
				}else{
					throw new RuntimeException("客户编号必须输入");
				}
			}catch(Exception e){
				e.printStackTrace();
				errMsg = e.getMessage();
			}
			if(num >0){
				out.println("<script type='text/javascript'>alert('删除成功');location.href='customer_list.jsp';</script>");
			}else{
				out.println("<script type='text/javascript'>alert('删除失败:需要删除客户的交易信息"+errMsg+"');history.back();</script>");
			}
		}else{
			list(request,resp);
		}
	}
	private void list(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String, Object> map=new HashMap<String, Object>();
		String customer_name=request.getParameter("customer_name");
		if(StringUtils.isNotNull(customer_name)){
			map.put("customer_name","%" + customer_name + "%");
		}
		A_customerService customerService = new A_customerServiceImpl();
		Integer pageIndex=StringUtils.str2Integer(request.getParameter("pageIndex"), 1);
		Integer pageSize = StringUtils.str2Integer(request.getParameter("pageSize"), 3);
		PageBean<A_customer> pageBean=customerService.findPageByCondition(pageIndex, pageSize, map);
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(pageBean);
		PrintWriter out=resp.getWriter();
		out.print(json);
	}
}
